package com.sharemarking.application.common.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.sharemarking.application.common.BaseSpecification;
import com.sharemarking.application.common.entity.Company;
import com.sharemarking.application.common.repository.CompanyRepo;

@Controller
@RequestMapping("company")
public class CompanyController {

	@Autowired
	private CompanyRepo cr;
	
	
	@RequestMapping("getAllCompany")
	@ResponseBody
	public List<Company> getAllDepartment(){
		List<Company> list=null;
		list=(List<Company>) cr.findAll();
		return list;
	}

	/**
	 * 公司数据列表
	 * 
	 * @param e
	 * @param page
	 * @param size
	 * @param model
	 */
	@GetMapping(value ="index")
	@PreAuthorize("hasPermission('sys:company',1)")
	public void index(Company e, Integer page, Integer size, Model model) {
		if (page == null) {
			page = 0;
		} else {
			page -= 1;
		}
		if (size == null) {
			size = 10;
		}
		// 按id降序排列
		Sort sort = new Sort(Direction.DESC, "id");
		PageRequest req = new PageRequest(page, size, sort);
		Page<Company> p = cr.findAll(new BaseSpecification<Company>(e),req);
		String pro="http://113.71.26.27:8080/tpl/public/uploadImage/companyLogo/";
		model.addAttribute("pro", pro);
		model.addAttribute("page", p);
		model.addAttribute("search", e);

	}

	/**
	 * 获取实体添加,编辑接口
	 * 
	 * @param obj
	 * @param model
	 * @return
	 */
	@GetMapping(value = "{id}")
	@PreAuthorize("hasPermission('sys:company',1)")
	public String get(Company obj, Model model) {
		if (obj.getId() != 0)
			obj = cr.findOne(obj.getId());
		String pro="http://113.71.26.27:8080/tpl/public/uploadImage/companyLogo/";
		model.addAttribute("pro", pro);
		model.addAttribute("obj", obj);

		return "company/form";
	}

	/**
	 * 企业添加和编辑
	 * 
	 * @param target
	 * @param PICN
	 * @return
	 * @throws IOException
	 */
	@PostMapping(value = "{id}")
	@Transactional
	@PreAuthorize("hasPermission('sys:company',#target.id==0?8:4)")
	public String index(HttpServletResponse response,Company target,@RequestParam("PICN") MultipartFile PICN) throws IOException {
			
		if (!PICN.isEmpty()) {
			// 文件上传
//			String PICName = null;
			
			MultipartFile file = PICN;
//			PICName = file.getOriginalFilename();
			// 把要上传的图片转换成流
			InputStream isRef = file.getInputStream();
 
			// 获取classes下的路径
//			String path = this.getClass().getClassLoader().getResource("").getPath() + "public/uploadImage/companyLogo/";
			String targetDir1 = this.getClass().getClassLoader().getResource("").getPath() + "public/uploadImage/companyLogo";
			File file1 = new File(targetDir1);
			file1.mkdirs();
			
			// 图片命名为loginName+Data+8位随机数.png
			Date now = new Date();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");// 可以方便地修改日期格式

			String Date = dateFormat.format(now);
			StringBuilder str = new StringBuilder();// 定义变长字符串

			// 随机生成数字，并添加到字符串
			Random random = new Random();
			for (int i = 0; i < 8; i++) {
				str.append(random.nextInt(10));
			}

//			String path2 = path + Date + str.toString() + ".png";
			String path3 = Date + str.toString() + ".png";
			
			File targetFile = new File(targetDir1, path3);
			// 通过输出流将图片写入到相应的地方
			FileOutputStream fosRef = new FileOutputStream(targetFile);
			IOUtils.copy(isRef, fosRef);
			// 添加
			if (target.getId() == 0) {
				// 将接收的文件保存到指定文件中
				target.setPhoto(path3);
				// 保存图片路径
				PICN.transferTo(targetFile);
				cr.save(target);
				ServletOutputStream stream = null;
		        try {  
		            stream = response.getOutputStream();  
		            QRCodeWriter writer = new QRCodeWriter();  
		            BitMatrix matrix = writer.encode("ok", BarcodeFormat.QR_CODE, 200, 200);
		            String path = this.getClass().getClassLoader().getResource("").getPath()+"public/uploadImage/companyLogo/";
		            System.out.println(path);
		            
		            File codeFile=new File(path+"code.png");
		            MatrixToImageWriter.writeToFile(matrix, "png", codeFile); 
		            System.out.println("ok");
		        } catch (WriterException e) {  
		            e.printStackTrace(); 
		            System.out.println("no");
		        } finally {  
		            if (stream != null) {  
		                stream.flush();  
		                stream.close();  
		            }  
		        };
				return "redirect:index";
			}
			// 编辑
			else {
				Company company = cr.findOne(target.getId());
				if (company == null) 
					return null;

				// 将接收的文件保存到指定文件中
				PICN.transferTo(targetFile);
				company.setNo(target.getNo());
				company.setName(target.getName());
				company.setType(target.getType());
				company.setTel(target.getTel());
				company.setAddress(target.getAddress());
				company.setTime(target.getTime());
				company.setDescriber(target.getDescriber());
//				company.setCode(target.getCode());
				company.setPhoto(path3);

			}
		}else{
			Company company = cr.findOne(target.getId());
			if (company == null) 
				return null;
			company.setNo(target.getNo());
			company.setName(target.getName());
			company.setType(target.getType());
			company.setTel(target.getTel());
			company.setAddress(target.getAddress());
			company.setTime(target.getTime());
			company.setDescriber(target.getDescriber());
//			company.setCode(target.getCode());
			
			return "redirect:index";
		}
		
		
		return "redirect:index";
	}
	/*//生成二维码
	
	public void getCore(HttpServletResponse response)throws ServletException, IOException{
		 
		ServletOutputStream stream = null;
        try {  
            stream = response.getOutputStream();  
            QRCodeWriter writer = new QRCodeWriter();  
            BitMatrix matrix = writer.encode("ok", BarcodeFormat.QR_CODE, 200, 200);
            String path = this.getClass().getClassLoader().getResource("").getPath()+"public/uploadImage/companyLogo/";
            System.out.println(path);
            
            File codeFile=new File(path+"code.png");
            MatrixToImageWriter.writeToFile(matrix, "png", codeFile); 
            System.out.println("ok");
        } catch (WriterException e) {  
            e.printStackTrace(); 
            System.out.println("no");
        } finally {  
            if (stream != null) {  
                stream.flush();  
                stream.close();  
            }  
        }  
	        
	 
	}*/
	
	
	/**
	 * 删除企业信息
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping(value = "{id}/delete")
	@Transactional
	public String delete(@PathVariable("id") Integer id) {
		cr.findOne(id).setDelFlag(true);
		return "redirect:../index";
	}
	
	//ajax验证公司的唯一性
	@PostMapping(value="checkName")
	@ResponseBody
	public String findByName(String param){
			return cr.findByName(param)!=null?"该公司已存在了":"y";
	}
	

}
